<script setup lang="ts">
import payService from '@/api/modules/pay/pay.ts'
import SafeTopContainer from '@/components/SafeTopContainer/SafeTopContainer.vue'
import useUserStore from '@/store/modules/user.ts'

const rechargeAmounts = ref(
  [
    { value: 100, label: '¥ 100' },
    { value: 200, label: '¥ 200' },
    { value: 300, label: '¥ 300' },
    { value: 400, label: '¥ 400' },
    { value: 500, label: '¥ 500' },
    { value: 1000, label: '¥ 1000' },
  ]
)
const selectedAmount = ref(0)
const customAmountValue = ref('')
const toast = useToast()

const userStore = useUserStore()
// 余额
const balance = computed(() => userStore.totalRechargeAmount)

onShow(() => {
  getUsersBalance()
})

async function getUsersBalance() {
  await userStore.getUserInfo()
}

function selectAmount(amount: number) {
  selectedAmount.value = amount
  customAmountValue.value = ''
}

function inputCustomAmount(e: any) {
  customAmountValue.value = e.target.value
  selectedAmount.value = 0
}

// 计算最终金额
const finalAmount = computed(() => {
  const custom = Number.parseFloat(customAmountValue.value)
  if (!Number.isNaN(custom) && custom > 0) {
    return Number(custom)
  }
  return selectedAmount.value
})

async function rechargeRecord() {
  const { code: wxCode } = await uni.login({ provider: 'weixin' })
  const payParams = {
    body: `充值${finalAmount.value}元`,
    code: wxCode,
    totalFeel: finalAmount.value,
  }
  const payRes = await payService.rechargeRecordApiPay(payParams)
  const { code, data } = payRes
  const paymentData = {
    // uni-app 官方推荐加上 provider，明确支付方式
    provider: 'wxpay', // 或 'alipay'
    timeStamp: data.timeStamp,
    nonceStr: data.nonceStr,
    package: data.package,
    signType: data.signType,
    paySign: data.paySign,
  } as UniApp.RequestPaymentOptions
  try {
    // 使用 await 等待支付结果
    await uni.requestPayment(paymentData)
    toast.success({
      msg: '充值成功',
      closed() {
        navigateBack()
      },
    })
  }
  catch (err) {
    toast.error({
      msg: '充值失败',
    })
  }
}
</script>

<template>
  <div class="recharge-container bg-top">
    <safe-top-container
      :padding-bottom="17"
      :padding-left="5"
    >
      <wd-navbar custom-class="!bg-transparent" title="充值中心" :bordered="false" left-arrow @click-left="navigateBack" />
    </safe-top-container>
    <div class="recharge-balance bg-balance mx-4 mb-2 mt-4 flex items-center justify-between rounded-lg p-5">
      <div class="text-white">
        <div class="">
          <div class="text-sm">
            当前账户余额（元）
          </div>
          <div class="text-[33px] text-white font-bold">
            {{ formatPrice(balance) }}
          </div>
        </div>
      </div>
      <img src="@/static/svg/money.svg" class="h-10 w-10">
    </div>
    <div class="mt-3 px-2">
      <div class="mb-4 rounded-lg bg-white p-4">
        <div class="mb-5 text-sm text-[#415AFFFF]">
          <wd-icon name="warn-bold" size="20px" />
          充值100元以上送10元，每人仅限使用一次
        </div>
        <div class="grid grid-cols-3 mb-4 gap-3">
          <div
            v-for="(amount, index) in rechargeAmounts"
            :key="index"
            class="amount-option flex flex-col cursor-pointer items-center justify-center border rounded-lg border-solid px-2 py-3 transition-all duration-300 hover:border-blue-500"
            :class="selectedAmount === amount.value ? 'border-[#6D80FF] bg-blue-50' : 'border-gray-200'"
            @click="selectAmount(amount.value)"
          >
            <div
              class="text-lg font-bold"
              :class="selectedAmount === amount.value ? 'text-[#6D80FF]' : 'text-gray-700'"
            >
              {{ amount.label }}
            </div>
          </div>
        </div>
        <div class="custom-amount">
          <div
            class="mb-2 flex items-center border border-gray-200 rounded-lg border-solid p-3"
          >
            <span class="mr-2 text-gray-500">¥</span>
            <input
              v-model="customAmountValue"
              placeholder="输入自定义金额"
              class="flex-1 border-none text-base outline-none"
              type="digit"
              @input="inputCustomAmount($event)"
            >
          </div>
        </div>
      </div>
      <div class="rounded-lg bg-white p-4">
        <div class="mb-2 text-lg text-gray-700 font-bold">
          充值说明
        </div>
        <div class="text-sm text-gray-500">
          <p>1、充值后余额可用于查询付费使用；</p>
          <p>2、未消费的余额可申请原路返回；</p>
          <p>3、有问题前往我的-联系客服；</p>
          <p> 4、参与充值赠送活动。余额不可退款，不可申请提现；</p>
        </div>
      </div>
    </div>
    <div class="recharge-btn mt-6 px-4">
      <wd-button
        type="primary" size="large" block :disabled="finalAmount === 0"
        @click="rechargeRecord()"
      >
        立即充值
      </wd-button>
    </div>
  </div>
</template>

<style scoped lang="scss">
.recharge-container{
  min-height: calc(100vh - 100px);
}
.recharge-balance{
  box-shadow: 0px 4px 6px  rgba(24, 105, 255, 0.3);
}

.recharge-btn{
  :deep(.wd-button){
    background: linear-gradient(90deg, rgba(24, 105, 255, 1) 0%, rgba(42, 150, 253, 1) 100%) !important;
    box-shadow: 0px 4px 6px  rgba(24, 105, 255, 0.3) !important;
  }
}
</style>
